//! edit data trait

use super::{Data, Item};
use json::JsonValue;
use std::fmt::Display;
pub trait Editor {
    fn add(&mut self, new_data: Item);
    fn remove(&mut self, index: usize);
    fn insert(&mut self, index: usize, new_data: Item);
    fn replace(&mut self, index: usize, new_data: Item);
    fn update<T: Display>(&mut self, index: usize, key: T, new_value: JsonValue);
}

impl Editor for Data {
    /// edit one column data
    /// #Example
    ///```
    /// use file_sql::*;
    /// let app = App::from_file("example.fql");
    /// let new_data = app.find_index(1);
    /// app.replace(0, "age", new_data.to_owned());
    ///```
    fn replace(&mut self, index: usize, new_data: Item) {
        self._data.remove(index);
        self._data.insert(index, new_data);
    }

    /// insert a column
    fn insert(&mut self, index: usize, new_data: Item) {
        self._data.insert(index, new_data);
    }

    /// delete data
    /// #Example
    ///```
    /// use file_sql::*;
    /// let app = App::from_file("example.fql");
    /// app.remove(1); // 删除第二行数据
    ///```
    fn remove(&mut self, index: usize) {
        self._data.remove(index);
    }

    fn update<T: Display>(&mut self, index: usize, key: T, new_value: JsonValue) {
        let mut new_data = self._data.remove(index);
        new_data.insert(key.to_string(), new_value);
        self._data.insert(index, new_data);
    }

    /// add data at last
    fn add(&mut self, new_data: Item) {
        self._data.push(new_data);
    }
}
